package org.jit.sose.service.Impl;

import org.jit.sose.OrderService;
import org.jit.sose.entity.User;
import org.jit.sose.feign.MemberServiceFeign;
import org.jit.sose.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Api(tags = "OrderService", description = "订单服务")
@RestController
public class OrderServiceImpl implements OrderService {

	@Autowired
	private MemberServiceFeign memberServiceFeign;

	@GetMapping("/")
	public String serviceInfo() {
		return "这是order服务";
	}

	@Override
	@ApiOperation(value = "创建订单")
	@ApiImplicitParam(name = "name", value = "用户名", paramType = "query", required = true, dataTypeClass = String.class)
	@GetMapping("/createOrder")
	public String createOrder(@RequestParam("name") String name) {
		User user = memberServiceFeign.getUserByName(name);
		return user.getName() + "下单了";
	}

	/**
	 * 为解决服务雪崩效应
	 */
	@GetMapping("/getOrderInfo")
	public String getOrderInfo() {
		log.info("order-当前线程：" + Thread.currentThread().getName());
		User user = memberServiceFeign.getUserByName("joey");
		return ResponseUtil.success(user.getName() + "查询了订单");
	}

	/**
	 * 解决服务雪崩效应<br>
	 * hystrix测试接口<br>
	 * @HystrixCommand作用：<br>
	 * 1.默认开启服务隔离方式 以线程池方式<br>
	 * 2.默认开启服务降级执行方法orderToMemberUserInfoHystrixFallback<br>
	 * 3.默认开启服务熔断机制<br>
	 * 服务降级方式一：在方法上标注
	 */
	@HystrixCommand(fallbackMethod = "getOrderInfoHystrixFallback")
	@GetMapping("/getOrderInfoHystrix")
	public String getOrderInfoHystrix() {
		log.info("order-hystrix-当前线程：" + Thread.currentThread().getName());
		User user = memberServiceFeign.getUserByName("wangyue");
		return ResponseUtil.success(user.getName() + "查询了订单");
	}

	/**
	 * hystrix服务降级调用方法<br>
	 * 若接口未在超时时长内响应，则执行降级方法
	 */
	public String getOrderInfoHystrixFallback() {
		return ResponseUtil.error(500, "Service is busy", "服务超时，请刷新页面重新加载");
	}

	/**
	 * 服务降级方式二：类
	 */
	@GetMapping("/getOrderInfoHystrixByClass")
	public String getOrderInfoHystrixByClass() {
		log.info("order-hystrix-当前线程：" + Thread.currentThread().getName());
		String result = memberServiceFeign.hello();
		return result;
	}

}
